#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <wait.h>

int main() {
    int pipefd[2];
    pid_t pid1, pid2;
    char buffer[256];

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    pid1 = fork();
    if (pid1 == 0) {
        // 子进程 P1
        close(pipefd[0]); // 关闭读端
        char message1[] = "Child P1 is sending My name wgm!";
        write(pipefd[1], message1, strlen(message1) + 1);
        close(pipefd[1]);
        exit(0);
    }

    pid2 = fork();
    if (pid2 == 0) {
        // 子进程 P2
        close(pipefd[0]); // 关闭读端
        time_t t;
        time(&t);
        char *time_str = ctime(&t);
        char message2[256];
        snprintf(message2, sizeof(message2), "Child P2 is sending the current time %s", time_str);
        write(pipefd[1], message2, strlen(message2) + 1);
        close(pipefd[1]);
        exit(0);
    }

    // 父进程
    close(pipefd[1]); // 关闭写端
    wait(NULL); wait(NULL); // 等待两个子进程结束
    while (read(pipefd[0], buffer, sizeof(buffer)) > 0) {
        printf("Parent received: %s\n", buffer);
    }
    close(pipefd[0]);
    return 0;
}